﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI;
using System.Text.RegularExpressions;
using System.Web.UI.HtmlControls;

namespace FooFun.Web.Controls
{
    public class PagerControl : Control
    {
        public int PageSize { get; set; }

        public int TotalCount { get; set; }

        public int PageCount
        {
            get
            {
                int pageCount = TotalCount / PageSize;
                if (TotalCount % PageSize != 0)
                {
                    pageCount++;
                }

                return pageCount;
            }
        }

        public PagerControl()
        {
            base.ChildControlsCreated = false;
        }

        protected override void CreateChildControls()
        {
            int pageCount = this.PageCount;
            for (int index = 0; index < pageCount; index++)
            {
                HtmlAnchor a = new HtmlAnchor();
                a.HRef = GetPagerUrl(index);
                a.InnerText = (index + 1).ToString();

                this.Controls.Add(a);
            }

            this.ChildControlsCreated = true;
        }

        public string GetPagerUrl(int pageIndex)
        {
            string url = this.Context.Request.RawUrl;

            int index = url.IndexOf("?");

            if (index == -1)
            {
                url = url + "?PageIndex=" + pageIndex;
            }
            else
            {
                bool exists = pageIndexRegex.IsMatch(url);

                if (!exists)
                {
                    url += "&PageIndex=" + pageIndex;
                }
                else
                {
                    url = pageIndexRegex.Replace
                        (url, "PageIndex=" + pageIndex);
                }
            }
            return url;
        }

        static Regex pageIndexRegex;

        static PagerControl()
        {
            pageIndexRegex = new Regex(@"PageIndex=(\d+)",
                RegexOptions.Compiled | RegexOptions.IgnoreCase);
        }
    }

    public class PagerItem : Control, INamingContainer
    {
        public int PageIndex { get; set; }
    }
}
